package imageProcessing.filter;

import imageProcessing.Duplicator;
import imageProcessing.ImageEvent;
import imageProcessing.ImageListener;

import java.awt.image.renderable.ParameterBlock;
import java.util.ArrayList;

import javax.media.jai.JAI;
import javax.media.jai.PlanarImage;

public class ThresholdFilter implements ImageListener{
	
	private ArrayList<ImageListener> _listeners;
	
	private int _low;
	private int _high;
	private int _map;

	private PlanarImage _image;
	
	public ThresholdFilter(){
		_listeners = new ArrayList<ImageListener>();
		_image = null;
		_low = -1;
		_high = -1;
		_map = -1;
	}

	public void notifyListeners() {
		
		if(this.allRectValuesSet()){
			ImageEvent ie  = new ImageEvent(this, _image);
			ArrayList<ImageListener> copy = Duplicator.copyListeners(_listeners);
			for (ImageListener listener : copy) {
				listener.imageChanged(ie);
			}
		}
	}
	
	
    public int getLow() {
		return _low;
	}

	public void setLow(int low) {
		this._low = low;
	}

	public int getHigh() {
		return _high;
	}

	public void setHigh(int high) {
		this._high = high;
	}

	public int getMap() {
		return _map;
	}

	public void setMap(int _map) {
		this._map = _map;
	}
	
	public void addImageListener(ImageListener imageListener){
		_listeners.add(imageListener);
	}
	
	public void removeImageListener(ImageListener imageListener){
		_listeners.remove(imageListener);
	}
	@Override
	public void imageChanged(ImageEvent imageEvent) {
		PlanarImage img = imageEvent.getImage();
    	double low[] = { _low,_low,_low };
		double high[] = { _high,_high,_high };
    	double map[] = { _map, _map, _map };
		ParameterBlock pb = new ParameterBlock();
		pb.addSource(img);
		pb.add(low);
		pb.add(high);
		pb.add(map);
		_image = JAI.create("threshold", pb);
		notifyListeners();
	}
	
	private boolean allRectValuesSet(){
		if(_low != -1 && _high != -1 && _map != -1){
			return true;
		}
		return false;
	}
}

